package 链表;

/**
 * @Author: biubiu0002
 * @Date: 2021-09-05 12:36
 **/
public class 反转链表Ⅱ反转链表中的一部分 {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        listNode1.next=listNode2;
        listNode2.next=listNode3;
        listNode3.next=listNode4;
        listNode4.next=listNode5;
        reverseBetween(listNode1,2,4);
        ListNode cur = listNode1;
        while(cur!=null){
            System.out.println(cur.val);
            cur=cur.next;
        }


    }

    public static ListNode reverseBetween(ListNode head, int left, int right) {
        if(left==right){
            return head;
        }

        ListNode prevNode=null,nxtNode=null,cur,dummy=new ListNode(-1);
        dummy.next=head;
        cur = dummy;
        int count=0;
        while(cur!=null){
            if(count+1==left){
                prevNode = cur;
            }
            if(count==right){
                nxtNode = cur.next;
            }
            cur=cur.next;
            count++;
        }
        ListNode pre = nxtNode,nxt;

        cur = prevNode.next;
        while(cur!=nxtNode){
            nxt=cur.next;
            cur.next=pre;
            pre =cur;
            cur=nxt;
        }
        prevNode.next=pre;
        return dummy.next;

    }
}
